var util = require('../../util.js');
//获取应用实例
var app = getApp();

// 初始化数据
var init = {

  // 数据
  data: {

    // 分页参数
    page: {

      // 当前页码
      index: 1,

      // 每页分页数
      size: 10,

      // 分页总数
      num: 1,

      // 加载锁
      lock: false
    },

    // 产品列表
    items: [],

    // 加载提示
    loadTips: '',

    // 订单状态
    status: '',
    first:true,

  },

  // 页面第一次加载
  onLoad: function (options) {
    var that = this;
    console.log(options);
    that.setData({
      status: options.status || ''
    })
    that.getData();
  },
  onShow: function () {
    if(this.data.first!=true){
      this.setData({
        'page.lock': false,
        // 当前页码
        'page.index': 1,

        // 每页分页数
        'page.size': 10,

        // 分页总数
        'page.num': 1,
        // 产品列表
        items: [],

        // 加载提示
        loadTips: '',

      })
      this.getData();
    }
    
  },
  // 上拉触底
  lower: function () {
    var that = this;
    that.getData();
  },

  // 切换tab
  tab: function (event) {

    var that = this;
    var status = event.currentTarget.dataset.status;
    console.log(that.data.page.lock);

    that.setData({
      status: status,
      page: {
        index: 1,
        size: 10,
        num: 1

      },
      items: []
    });
    that.getData();

  },

  // 提醒卖家发货
  remindSeller: function (event) {
    var orderId = event.currentTarget.dataset.orderid;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api,
        data: {
          app: 'buyer_order',
          act: 'remind_seller',
          order_id: orderId,
          t_session: session
        },
        success: function (res) {
          var data = res.data;
          console.log(data);
          if (data.done) {
            wx.showToast({
              title: data.retval.msg,
              icon: 'success',
              duration: 2000
            })
          }
        }
      })
    })
  },
  //取消订单
  cancel:function(res){
    var that = this;
    that.setData({
      'page.lock':false,
      'page.index': 1,
       items:[]
    });
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api,
        data: {
          app:'order',
          act:'cancel_order',
          order_id: res.currentTarget.dataset.orderid,
          t_session:session
        },
        success:function(res){
          var data = res.data;
          if(data.done&&data.retval){
            that.getData();
          } else {
            wx.showToast({
              title: '请重试',
              icon:'loading'
            })
          }
        },
        fail:function(res){
          wx.showToast({
            title: '接口连接失败',
            icon:'loading'
          })
        }
      })
    })
    
  },
  // 立即支付
  buyNow: function (event) {
    console.log(event.currentTarget.dataset.amount);
    app.callToPay(event.currentTarget.dataset.orderid, event.currentTarget.dataset.amount);
  },

  // 确认收货
  confirmOrder: function (event) {
    var that = this;
    var orderId = event.currentTarget.dataset.orderid;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api,
        data: {
          app: 'buyer_order',
          act: 'confirm_order',
          order_id: orderId,
          t_session: session
        },
        success: function (res) {
          var data = res.data;
          console.log(data);
          if (data.done) {
            wx.showToast({
              title: data.retval.msg,
              icon: 'success',
              duration: 2000,
              success: function () {
                that.getData();
              }
            })
          }
        }
      })
    })
  },

  // 查看物流（物流时时更新的，加时间戳防止跳转缓存）
  viewLogistics: function (event) {
    var that = this;
    var orderId = event.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/pages/logistics/logistics?order_id=' + orderId + '&random=' + Math.random(),
    })
  },

  // 获取数据
  getData: function () {
    var that = this;
    var page = that.data.page;
    console.log(page.lock);
    // 加锁
    if (page.lock) return;
    that.setData({
      'page.lock': true
    });

    app.getLoginSession(function (session) {

      if (page.num >= page.index) {

        // 加载前
        that.setData({
          loading: false,
          loadTips: that.data.loading ? '' : '加载中...'
        });


        wx.request({

          // 请求地址
          url: app.api,

          // 请求参数
          data: {
            app: 'buyer_order',
            act: 'buyerOrder',
            search: that.data.status,
            page: page.index,
            t_session: session
          },

          // 请求成功
          success: function (res) {
            var data = res.data;
            console.log(data);


            that.setData({
              'page.num': parseInt(Math.ceil(data.retval.total_amount / that.data.page.size)),
              'page.lock': false,
              first:false
            });

            console.log('总页码：' + that.data.page.num + '，当前页码：' + that.data.page.index+that.data.page.lock);

            // 完全没有数据
            if (that.data.page.num == 0) {
              that.setData({
                loadTips: '暂无数据！'
              })
              return
            }

            // 有数据，累加
            var items = data.retval.orders;

            // 处理时间
            for (var i = 0; i < items.length; i++) {
              if (items[i].left_time ){
                var leftTime = items[i].left_time.split(' - ');
                items[i].left_time = leftTime[0] + '天' + leftTime[1] + '时' + leftTime[2] + '分'
              }
            }

            if (items && items.length) {
              that.setData({
                items: that.data.items.concat(that.deallist(items))
              })
            }
            console.log(that.data.items);
            // 如果只有一页数据
            if (that.data.page.num == 1) {
              that.setData({
                loadTips: '无更多数据！'
              })
            }

            // 累加页码
            that.setData({
              'page.index': ++page.index,
              'page.lock': false
            });

          },

          // 请求失败
          fail: function () {
            console.log('aa');
            that.setData({
              loading: true,
              loadTips: '加载数据失败！'
            })
          },

          // 请求结束
          complete: function () {

            // 解锁
            that.setData({
              'page.lock': false
            })
          }

        });
      } else {
        that.setData({
          loadTips: '无更多数据！'
        })
      }
    })
  },
  deallist(list) {
    if (list && Array.isArray(list)) {
      list.forEach((item) => {
        console.log(item);
        item.add_time = util.formatDate(new Date(item.add_time * 1000), 'YY-MM-dd mm:ss');
        for (var i = 0; i < item.order_goods.length;i++){
          item.shipping_fee = parseInt(item.shipping_fee)+parseInt(item.order_goods[i].quantity)
        }
      })
      return list
    }
  },

};

// 注册页面
Page(init);
